package com.chipcoo.shiro.realm;

import com.chipcoo.UserPrincipal;
import com.chipcoo.models.gen.Passport;
import com.chipcoo.models.gen.User;
import com.chipcoo.models.gen.UserProfile;
import com.chipcoo.services.UserService;
import com.chipcoo.utils.ValidateUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * LOGIN 的验证最终在这里实现
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
     * 认证回调函数, 登录时调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AccountException,UnknownAccountException,DisabledAccountException,ExcessiveAttemptsException,IncorrectCredentialsException

    {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        // 校验用户名密码
        String username = token.getUsername();


        Passport passport = null;
        User user = null;
        if (ValidateUtils.isEmail(username)) {
            passport = userService.getAuthenticationPassport(username,2);
        } else if(ValidateUtils.isPhone(username)) {
            passport = userService.getAuthenticationPassport(username,1);
        } else{
            passport = userService.getAuthenticationPassport(username,3);
        }

        if( null==passport) throw new UnknownAccountException();

        user = userService.getUser(passport.getUserID());
        if (null == user) throw new UnknownAccountException();


        if (user.getLockoutEnabled()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date lockeForever;
            try {
                lockeForever = sdf.parse("2049-01-01");
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new DisabledAccountException();
            }

            if (user.getLockoutEnd().after(lockeForever) || user.getLockoutEnd().equals(lockeForever))
                throw new DisabledAccountException();
            else {
                Date dtNow = new Date();
                if (dtNow.before(user.getLockoutEnd()))
                    throw new ExcessiveAttemptsException();
            }
        }

        if(passport.getPassportType()==1
                ||passport.getPassportType()==2
                ){
            String password = new String(token.getPassword()).trim();

            if (!password.equalsIgnoreCase(user.getPasswordHash())) {
                userService.loginFailed(user);
                throw new IncorrectCredentialsException();
            }
        }

        //IncorrectCredentialsException
        UserProfile userProfile = userService.getProfile(user.getId());
        UserPrincipal model = new UserPrincipal(token.getUsername(),user,userProfile);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(model, token.getPassword(), getName());
        userService.loginSuccess(passport.getId(),user);
        return authenticationInfo;
    }
    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserPrincipal principal =null;
        try {
            principal = (UserPrincipal)principals.fromRealm(getName()).iterator().next();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        if(null==principal) return null;

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("test:view");

        return info;
    }


}

